package listbyorder.access201_300.test289;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/6/28 14:39
 */
public class Solution1 {

    public void gameOfLife(int[][] board) {
        int r = board.length;
        int c = board[0].length;
        int[][] temp = new int[r][c];
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                temp[i][j] = cal(board, i, j);
            }
        }
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                board[i][j] = temp[i][j];
            }
        }
    }

    private int cal(int[][] board, int i, int j) {
        int count = getCount(board, i + 1, j) +
                getCount(board, i + 1, j + 1) +
                getCount(board, i + 1, j - 1) +
                getCount(board, i, j + 1) +
                getCount(board, i, j - 1) +
                getCount(board, i - 1, j + 1) +
                getCount(board, i - 1, j) +
                getCount(board, i - 1, j - 1);
        if (board[i][j] == 1) {
            return (count < 2 || count > 3) ? 0 : 1;
        } else {
            return count == 3 ? 1 : 0;
        }
    }

    private int getCount(int[][] board, int i, int j) {
        if (i < 0 || i == board.length || j < 0 || j == board[0].length || board[i][j] == 0) return 0;
        return 1;
    }
}
